import React from 'react'
import { Space, Tag } from 'antd'
import './index.css'
import { useLocation, useNavigate } from 'react-router-dom'
import { useSelector, useDispatch } from 'react-redux'
import { closeTab, setCurrentMenu } from '../../store/reducers/tab'

export default function CommonTag() {
    const dispatch = useDispatch()
    const action = useLocation()
    const navigate = useNavigate()
    const tabList = useSelector(state => state.tab.tabList)
    const currentMenu = useSelector(state => state.tab.currentMenu)
    const handleClose = (tag, index) => {
        console.log(tabList)
        let length = tabList.length - 1;
        dispatch(closeTab(tag));
        // 如果关闭的不是当前的tag
        if (tag.path !== action.pathname) {
            return;
        }
        if (index === length) {
            const curData = tabList[index - 1];
            dispatch(setCurrentMenu(curData))
            navigate(curData.path)
        } else {
            // 至少一个
            if (tabList.length > 1) {
                const nextData = tabList[index + 1];
                dispatch(setCurrentMenu(nextData))
                navigate(nextData.path)
            }
        }

    }

    const handleChange = (tag) => {
        dispatch(setCurrentMenu(tag))
        navigate(tag.path)
    }

    // tag的显示
    const setTag = (flag, item, index) => {
        return (
            flag ?
                <Tag color='#55acee' closeIcon onClose={() => handleClose(item, index)} key={item.name}>{item.label}</Tag>
                :
                <Tag onClick={() => handleChange(item)} key={item.name}>{item.label}</Tag>
        )
    }
    return (
        <div>
            <Space size={[0, 8]} wrap className='common-tag'>
                {/* <Tag>首页</Tag>
                <Tag color='#55acee' closeIcon onClose={handleClose}>用户列表</Tag> */}
                {
                    currentMenu.name &&
                    tabList.map((item, index) => (setTag(item.path === currentMenu.path, item, index)))
                }
            </Space>
        </div>
    )
}
